package com.bulletelc.apollopre.module.deal.clearing;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bulletelc.apollopre.MyApplication;
import com.bulletelc.apollopre.R;
import com.bulletelc.apollopre.constants.GlobalConfig;
import com.bulletelc.apollopre.constants.IntentCode;
import com.bulletelc.apollopre.constants.NetWorkPath;
import com.bulletelc.apollopre.entity.AddressDetailBean;
import com.bulletelc.apollopre.entity.CartListBean;
import com.bulletelc.apollopre.entity.InvoiceSelectBean;
import com.bulletelc.apollopre.entity.OrderConfirmBean;
import com.bulletelc.apollopre.entity.OrderDataBean;
import com.bulletelc.apollopre.framework.MVPBaseActivity;
import com.bulletelc.apollopre.module.deal.pay.PayCenterActivity;
import com.bulletelc.apollopre.module.main.center.address.list.AddressActivity;
import com.bulletelc.apollopre.module.web.WebPageActivity;
import com.bulletelc.apollopre.utils.MyUtil;
import com.bulletelc.apollopre.utils.ToastUtil;
import com.bulletelc.apollopre.widget.FoolBar;
import com.bulletelc.apollopre.widget.NestedExpandableListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * author: lhl
 * date  : 2018/01/20
 * desc  : 结算页(填写订单页)
 */

public class ClearingActivity extends MVPBaseActivity<ClearingContract.View, ClearingPresenter> implements ClearingContract.View,
        View.OnClickListener,FoolBar.ClickCallback, ClearingListAdapter.OnInstallCheckChangeListener {
    private FoolBar foolBar;

    // views
    private ScrollView scrollView;
    private RelativeLayout rlNoAddress;
    private TextView tvNoAddress;
    private RelativeLayout rlAddress;
    private TextView tvReceiverHint;
    private TextView tvReceiver;
    private TextView tvPhone;
    private TextView tvAddress;
    private NestedExpandableListView elvOrderList;
    private TextView tvBillType;
    private ImageButton iBtnTo;
    private CheckBox cbProtocol;
    private Button btnProtocol;
    private TextView tvInstallMoney;
    private TextView tvPayMoney;
    private Button btnSubmit;
    private LinearLayout llInstallFeePanel;

    // data
    private OrderConfirmBean confirmBean;
    private ClearingListAdapter clearingListAdapter;
    private int addressId;
    private double total;
    private double totalInstallFee;
    private int install = 1;

    @Override
    public int getLayoutRes() {
        return R.layout.clearing_activity;
    }

    @Override
    public void assignViews() {
        foolBar = findView(R.id.flBar);
        foolBar.setTitle(this.getResources().getString(R.string.order_clearing));
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        rlNoAddress = (RelativeLayout) findViewById(R.id.rlNoAddress);
        tvNoAddress = (TextView) findViewById(R.id.tvNoAddress);
        rlAddress = (RelativeLayout) findViewById(R.id.rlAddress);
        tvReceiverHint = (TextView) findViewById(R.id.tvReceiverHint);
        tvReceiver = (TextView) findViewById(R.id.tvReceiver);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvAddress = (TextView) findViewById(R.id.tvAddress);
        elvOrderList = findViewById(R.id.elvOrderList);
        tvBillType = (TextView) findViewById(R.id.tvBillType);
        iBtnTo = (ImageButton) findViewById(R.id.iBtnTo);
        cbProtocol = (CheckBox) findViewById(R.id.cbProtocol);
        btnProtocol = (Button) findViewById(R.id.btnProtocol);
        tvInstallMoney = (TextView) findViewById(R.id.tvInstallMoney);
        tvPayMoney = (TextView) findViewById(R.id.tvPayMoney);
        btnSubmit = (Button) findViewById(R.id.btnSubmit);
        llInstallFeePanel = (LinearLayout) findViewById(R.id.llInstallFeePanel);
    }

    @Override
    public void setListener() {
        foolBar.setClickCallback(this);
        rlNoAddress.setOnClickListener(this);
        rlAddress.setOnClickListener(this);
        btnSubmit.setOnClickListener(this);
        btnProtocol.setOnClickListener(this);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }
        confirmBean = (OrderConfirmBean) intent.getSerializableExtra(IntentCode.EXTRA_KEY_CONFIRM_ORDER_DATA);
        totalInstallFee = confirmBean.getInstall_fee_total();
        total = Double.parseDouble(confirmBean.getAll_grand_total()) + totalInstallFee;
        clearingListAdapter = new ClearingListAdapter(this, confirmBean.getOrder_list());
        clearingListAdapter.setOnInstallCheckChangeListener(this);
        elvOrderList.setAdapter(clearingListAdapter);
        expandListView();
        tvPayMoney.setText("¥" + MyUtil.format2(total));
        if (totalInstallFee != 0) {
            llInstallFeePanel.setVisibility(View.VISIBLE);
            tvInstallMoney.setText("¥" + MyUtil.format2(totalInstallFee));
        }
        OrderConfirmBean.Address address = confirmBean.getAddress();
        if (address != null) {
            rlNoAddress.setVisibility(View.INVISIBLE);
            rlAddress.setVisibility(View.VISIBLE);
            tvReceiver.setText(address.getUserName());
            tvPhone.setText(address.getPhone_no());
            tvAddress.setText(address.getRegion_label()+" "+address.getApartment_address());
            addressId = address.getId();
        } else {
            rlNoAddress.setVisibility(View.VISIBLE);
            rlAddress.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    protected ClearingPresenter createPresenter() {
        return new ClearingPresenter();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.rlNoAddress:
                goToAddressActivity();
                break;

            case R.id.rlAddress:
                goToAddressActivity();
                break;

            case R.id.btnSubmit:
                checkAddress();
                break;

            case R.id.btnProtocol:
                purchaseAgreement();
                break;
        }
    }

    @Override
    public void onSuccessPlaceOrder(OrderDataBean orderDataBean) {
        if (orderDataBean != null) {
            Intent intent = new Intent(this, PayCenterActivity.class);
            intent.putExtra(IntentCode.EXTRA_KEY_ORDER_DATA, orderDataBean);
            startActivity(intent);
            finish();
        } else {
            Toast.makeText(this, "数据发生错误", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onFailPlaceOrder(String fail) {
        Toast.makeText(this, fail, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onErrorPlaceOrder(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    public void onSuccessCheckAddress(boolean b) {
        if (b) {
            placeOrder();
        }
    }

    @Override
    public void onFailCheckAddress(String fail) {
        ToastUtil.showLongToast(this, fail);
    }

    @Override
    public void onErrorCheckAddress(String error) {
        ToastUtil.showLongToast(this,R.string.network_msg);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case IntentCode.REQUEST_CODE_CLEARING_TO_LIST:
                if (resultCode == IntentCode.RESULT_CODE_ADDRESS_LIST_RETURN_CLEARING) {
                    AddressDetailBean address = (AddressDetailBean) data.getSerializableExtra(IntentCode.EXTRA_KEY_ADDRESS_DATA);
                    setAddress(address);

                }
                break;

            case IntentCode.REQUEST_CODE_CLEARING_TO_INVOICE:
                if (resultCode == IntentCode.RESULT_CODE_INVOICE_RETURN_CLEARING) {
                    InvoiceSelectBean invoiceSelectBean = (InvoiceSelectBean) data.getSerializableExtra(IntentCode.EXTRA_KEY_INVOICE_SELECT_BEAN);
                    setInvoice(invoiceSelectBean);
                }
                break;
        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {

    }

    /**
     * 进入地址列表界面
     */
    private void goToAddressActivity() {
        Intent intent = new Intent(this, AddressActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_FROM_CLEARING, true);
        startActivityForResult(intent, IntentCode.REQUEST_CODE_CLEARING_TO_LIST);
    }

    /**
     * 将listview的子listview展开
     */
    private void expandListView() {
        for (int i = 0, size = clearingListAdapter.getGroupCount(); i < size; i++) {
            elvOrderList.expandGroup(i);
        }
    }

    /**
     * 提交订单
     */
    private void placeOrder() {
        String json = null;
        List<CartListBean> orderList = confirmBean.getOrder_list();
        JSONObject object = new JSONObject();
        try {
            JSONArray cartListArray = new JSONArray();
            JSONArray invoiceList = new JSONArray();
            for (int i = 0, size = orderList.size(); i < size; i++) {
                JSONObject itemObject = new JSONObject();
                JSONArray itemIdArray = new JSONArray();
                JSONObject invoiceObject = new JSONObject();
                for (int j = 0, sizeJ = orderList.get(i).getProduct_list().size(); j < sizeJ; j++) {
                    CartListBean.CartProductListBean bean = orderList.get(i).getProduct_list().get(j);
                    itemIdArray.put(Integer.valueOf(bean.getId()));

                }
                itemObject.put("supplier_id", Integer.valueOf(orderList.get(i).getSupplier_id()));
                itemObject.put("cart_item_id", itemIdArray);
                cartListArray.put(itemObject);

                //发票
                if (orderList.get(i).getInvoice_id() != 0) {
                    invoiceObject.put("supplier_id", Integer.valueOf(orderList.get(i).getSupplier_id()));
                    invoiceObject.put("invoice_id", orderList.get(i).getInvoice_id()); //发票号是int类型
                    invoiceList.put(invoiceObject);
                }

            }

            object.put("cart_item_list", cartListArray);
            if (invoiceList.length() > 0) {
                object.put("invoice_list", invoiceList); //发票,非必填
            }
            object.put("address_id", addressId); //
            object.put("eshop_id", 1);
            object.put("is_install", install);
            object.put("install_price", totalInstallFee);
            json = object.toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.i("json789456", json);
        if (json != null) {
            presenter.placeOrder(json, MyApplication.getToken());
        } else {
            Toast.makeText(this, "请求参数错误", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 设置地址
     *
     * @param address
     */
    private void setAddress(AddressDetailBean address) {
        if (address != null) {
            rlNoAddress.setVisibility(View.INVISIBLE);
            rlAddress.setVisibility(View.VISIBLE);
            tvReceiver.setText(address.getUserName());
            tvPhone.setText(address.getPhone_no());
            tvAddress.setText(address.getRegion_label() + " " + address.getApartment_address());
            addressId = address.getId();

        } else {
            Toast.makeText(this, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 设置发票
     *
     * @param invoiceSelectBean
     */
    private void setInvoice(InvoiceSelectBean invoiceSelectBean) {
        if (invoiceSelectBean != null) {
            int groupPosition = invoiceSelectBean.getGroupPosition();
            confirmBean.getOrder_list().get(groupPosition).setInvoice_id(invoiceSelectBean.getId());
            confirmBean.getOrder_list().get(groupPosition).setInvoice_name(invoiceSelectBean.getName());
            clearingListAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(this, "数据有误", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 购买协议
     */
    private void purchaseAgreement() {
        Intent intent = new Intent(this, WebPageActivity.class);
        intent.putExtra(IntentCode.EXTRA_KEY_URL, NetWorkPath.GET_PURCHASE_AGREEMENT);
        intent.putExtra(IntentCode.EXTRA_WEB_PAGE_FLAG, GlobalConfig.WEB_PAGE_FOR_AGREEMENT);
        startActivity(intent);
    }

    /**
     * 检查是否可以下单
     */
    private void checkAddress() {
        if (!cbProtocol.isChecked()) {
            Toast.makeText(this, "请确认已阅读并同意协议", Toast.LENGTH_SHORT).show();
            return;
        }
        presenter.checkAddress(addressId);
    }

    @Override
    public void checkInstall(int groupPos, boolean b) {
        List<CartListBean> orderList = confirmBean.getOrder_list();
        double subInstallFee = orderList.get(groupPos).getSub_install_fee();
        if (!b) {
            totalInstallFee -= subInstallFee;
            total -= subInstallFee;
            install = 0;
        } else {
            totalInstallFee += subInstallFee;
            total += subInstallFee;
            install = 1;
        }
        tvInstallMoney.setText(MyUtil.format2(totalInstallFee));
        tvPayMoney.setText(MyUtil.format2(total));

    }
}
